function loadChatBox(chatboxId) {
    $(document).ready(function() {
        $("#"+chatboxId+"-send-button").click(function() {
            chatboxSend(chatboxId);
        });
        $("#"+chatboxId+"-input").keypress(function(event) {
            if(event.keyCode == 13) chatboxSend(chatboxId);
        });
        refreshChatbox(chatboxId, true);
    });
}

function refreshChatbox(chatboxId, sTout) {
    jQuery.ajax({
        url: '/chatbox/chatbox/'+chatboxId+'/',
        complete: function(jqXHR, textStatus) {
            if(textStatus == "success") {
                $("#"+chatboxId+"-data").html(jqXHR.responseText);
            }
            else if(textStatus == "notmodified") {

            }
            else {
                $("#"+chatboxId+"-data").html("<?php echo Configure::read("Autoconfig.chatboxConnectErrorMessage"); ?>");
            }
        }
    });
    if(sTout) setTimeout("refreshChatbox('"+chatboxId+"')", <?php echo Configure::read("Autoconfig.chatboxCheckFrequency"); ?>);
}

function chatboxSend(chatboxId) {
    if($("#"+chatboxId+"-guest").val() == '1' && $("#"+chatboxId+"-nick-input").val() == "") alert("<?php echo Configure::read("Autoconfig.chatboxNickRequiredMessage"); ?>");
    else if($("#"+chatboxId+"-input").val() == "") alert("<?php echo Configure::read("Autoconfig.chatboxEmptyContentMessage"); ?>");
    else {
        jQuery.ajax({
            url: '/chatbox/post/'+chatboxId+'/',
            type: 'POST',
            data: {
                guest: <?php echo(($authorized? "0" : "1")); ?>,
                <?php echo(($authorized? "user_id: '".$authorizedUser['id']."'," : 'nick: $("#"+chatboxId+"-nick-input").val(),')); ?>
                content: $("#"+chatboxId+"-input").val()
            },
            dataType: 'html',
            complete: function(jqXHR, textStatus) {
                if(textStatus == "success") {
                    $("#"+chatboxId+"-data").html(jqXHR.responseText);
                    $("#"+chatboxId+"-input").val("");
                }
                else if(textStatus == "notmodified") {

                }
                else {
                    $("#"+chatboxId+"-data").html("<?php echo Configure::read("Autoconfig.chatboxConnectErrorMessage"); ?>");
                }
            }
        });
    }
}

function chatboxDeleteMessage(msgId, chatboxId) {
    jQuery.ajax({
        url: '/admin/chatbox/fastdelete/'+msgId+'/',
        complete: function(jqXHR, textStatus) {
            if(textStatus == "success") {
                alert(jqXHR.responseText);
                refreshChatbox(chatboxId, false);
            }
            else if(textStatus == "notmodified") {

            }
            else {
                alert("Nie udało się usunąć z powodu błędu połączenia.");
            }
        }
    });
    
}